#include "sphere.h"
#include "material.h"

#include <GL/glut.h>
#include <cmath>
#include <float.h>

// use qglviewer namespace to avoid having to write qglviewer:: to use
// qglviewer-defined classes
using namespace qglviewer;
using namespace std;

Sphere::Sphere()
{
  init(1.0f, 20, 20);
}

Sphere::Sphere(float radius, int ntheta, int nphi)
{
  init(radius, ntheta, nphi);
}

void Sphere::init(float r, int ntheta, int nphi)
{
  // Set the radius for openGL
  setRadius(r);
  setNtheta(ntheta);
  setNphi(nphi);
}

void Sphere::draw() const
{
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glMultMatrixd(frame().matrix());
  glColor3fv(material().diffuseColor());
  gluSphere(gluNewQuadric(), radius(), ntheta(), nphi());
  glPopMatrix();
}

/* Does the ray intersect any of the triangles composing
 * the current sphere ?
 */
bool Sphere::intersect(const Ray& ray, Hit& hit) const
{
  float dist = FLT_MAX;

  // to remove "unused parameter" warnings - to be removed
  Q_UNUSED(ray)
  Q_UNUSED(hit)

  // TODO

  return dist != FLT_MAX;
}

/* Parse the XML for elements of the Sphere
 */
void Sphere::initFromDOMElement(const QDomElement& e)
{
  // init the object part
  Object::initFromDOMElement(e);

  // Parse for ntheta, nphi, radius
  float radius = e.attribute("radius", "1.0").toFloat();
  int ntheta = e.attribute("ntheta", "10").toInt();
  int nphi = e.attribute("nphi", "10").toInt();
  init(radius, ntheta, nphi);
}

